package top.yisen614.sharedelement.util

import android.os.AsyncTask
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject


/**
 * created by 16539
 * 2019/12/11
 */
class ImageLoader : AsyncTask<String, Int, MutableList<Image>>() {

    private val images = mutableListOf<Image>()

    override fun doInBackground(vararg p0: String?): MutableList<Image> {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url("https://pic.sogou.com/pics/channel/getAllRecomPicByTag.jsp?category=%E7%BE%8E%E5%A5%B3&tag=%E6%96%87%E8%89%BA&start=0&len=1000")
            .build()

        val response = client.newCall(request).execute()
        val jsonString = response.body()!!.string()

        return parseImages(jsonString)
    }

    private fun parseImages(jsonString: String): MutableList<Image> {
        val body = JSONObject(jsonString)
        val array = body.getJSONArray("all_items")
        for (i in 0 until array.length()) {
            val obj = array.getJSONObject(i)
            images.add(
                Image(obj.getString("id"), obj.getString("pic_url"), obj.getString("id"))
            )
        }
        return images
    }

}